package org.csu.mypetstore.util;

import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.csu.mypetstore.common.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 若存在父类关系，父类则写在下面
     */

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)// 400
    @ResponseBody
    public CommonResponse<Object> handldMissingServletRequestParameterException(MissingServletRequestParameterException e){
//        e.printStackTrace();
        logger.error(e.getMessage());
        return CommonResponse.createForError("缺少参数");
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)// 500
    @ResponseBody
    public CommonResponse<Object> handldConstraintViolationException(ConstraintViolationException e){
        logger.error(e.getMessage());
        return CommonResponse.createForError(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)// 500
    @ResponseBody
    public CommonResponse<Object> handldException(Exception e){
        logger.error(e.getMessage());
        return CommonResponse.createForError("服务器异常");
    }

}
